package money

import (
	"game_server/logic/db/api"
	"game_server/logic/db/handler"
	"game_server/logic/db/mark"
	. "game_server/logic/internal"
)

type moneyDal struct {
}

var dal = new(moneyDal)

func init() {
	Skeleton.AfterInit(func() {
		db_api.Register(dal)
	})
}

func (*moneyDal) Name() string {
	return "money"
}

func (*moneyDal) DBMark() db_mark.Enum {
	return db_mark.Money
}

func (*moneyDal) OnSaveDB(session *db_handler.Session, args *db_handler.SaveArgs) (result *db_handler.SaveResult, errs []error) {
	player := args.Player
	money := player.Money

	count, err := session.Where("PlayerId = ?", player.Id()).Update(money)
	if err != nil {
		errs = append(errs, err)
		return
	}

	if count < 1 {
		if _, err = session.Insert(money); err != nil {
			errs = append(errs, err)
			return
		}
	}

	return
}

func (*moneyDal) OnLoadDB(session *db_handler.Session, args *db_handler.LoadArgs) (result *db_handler.LoadResult, err error) {
	player := args.Player
	_, err = session.Get(player.Money)
	if err != nil {
		return
	}

	return
}
